package com.atguigu.spzx.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.atguigu.spzx.mapper.CategoryMapper;
import com.atguigu.spzx.model.vo.product.CategoryExcelVo;

import java.util.List;

public class ExcelListener<T> extends AnalysisEventListener<T> {
    /**
     每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<CategoryExcelVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    //获取mapper对象
    private CategoryMapper categoryMapper;
    public ExcelListener(CategoryMapper categoryMapper) {
        //初始化的时候设置mapper属性,将需要操作的mapper以构造的方式传递进来,这样就可以避免进行多线程的修改
        this.categoryMapper = categoryMapper;
    }


    // 每解析一行就会调用一下当前方法
    @Override
    public void invoke(T o, AnalysisContext analysisContext) {


        // 将当前对象转为可操作对象
        CategoryExcelVo data = (CategoryExcelVo)o;
        cachedDataList.add(data);
        if(cachedDataList.size() > BATCH_COUNT){
            //调用方法将数据进行存储
            saveData();
            //存储完毕之后,进行清理list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }
    private void saveData() {
        categoryMapper.batchInsert(cachedDataList);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //所有的操作完成之后进行调用
        saveData();

    }
}
